<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;
use app\models\AuthItem;
use app\models\AuthItemChild;
use mdm\admin\models\searchs\Assignment as AssignmentSearch;
use app\models\User;
use mdm\admin\components\Configs;
use mdm\admin\models\Assignment;
use yii\helpers\ArrayHelper;

class QxAssignmentController extends \mdm\admin\controllers\AssignmentController
{

    /**
     * {@inheritdoc}
     * @see \yii\web\Controller::beforeAction()
     */
    public function beforeAction($action)
    {
        date_default_timezone_set('PRC');//设置时间时区为中国
        header("Content-type:application/x-www-form-urlencoded text/html; charset=utf-8");//设置格式为utf-8
        header('Access-Control-Allow-Origin:'.\Yii::$app->components['allowOutHttp']);
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:X-Requested-With, origin, content-type, accept');
        header('Access-Control-Allow-Credentials: true');
        return true;
    }

    /**
     * 将数据打包成 layui可以识别的数据格式
     * @param $count
     * @param $all
     * @return array
     */
    public function packData($count,$all){
        $res = [];
        $res['code'] = 0;
        $res['msg'] = "";
        $res['count'] = $count;
        $res['data'] = $all;
        return json_encode((object)$res);
    }

    public function actionList()
    {
        if ($this->searchClass === null) {
            $searchModel = new AssignmentSearch();
            $dataProvider = $searchModel->search(\Yii::$app->getRequest()->post(), $this->userClassName, $this->usernameField);
        } else {
            $class = $this->searchClass;
            $searchModel = new $class;
            $dataProvider = $searchModel->search(\Yii::$app->getRequest()->post());
        }
        $post = \Yii::$app->getRequest()->post();
        if ($searchModel->load($post,'AssignmentSearch')){
            $dataProvider->query
                ->andFilterWhere(['like','y.ygmc',$post['AssignmentSearch']['ygmc']])
                ->andFilterWhere(['like','y.zxhm',$post['AssignmentSearch']['zxhm']])
                ->andFilterWhere(['like','user.username',$post['AssignmentSearch']['username']])
                ->andFilterWhere(['like','user.email',$post['AssignmentSearch']['email']])
                ->andFilterWhere(['like','y.yggh',$post['AssignmentSearch']['yggh']]);
        }
        $dataProvider->query->select('y.ygmc,y.yggh,y.zxhm,user.*');
        $dataProvider->query->leftJoin('crm_system_ygxx as y','y.user_id=user.id');
        $dataProvider->query->limit($_POST['limit']);
        $dataProvider->query->offset($_POST['limit']*($_POST['page']-1));
        $all = $dataProvider->query->asArray()->all();
        return $this->packData($dataProvider->count,ArrayHelper::toArray($all));
    }

    /**
     * 返回不重复的数组
     * @param $rows
     * @return array
     */
    public function populate($rows)
    {
        if ($this->indexBy === null) {
            return $rows;
        }
        $result = [];
        foreach ($rows as $row) {
            $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
        }

        return $result;
    }

    /**
     * Displays a single Assignment model.
     * @param  integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $opts = $this->getItems_($model);
        $res['data'] = $opts;
        $res['res'] = 1;
        return json_encode($res);
    }

    /**
     * Get all available and assigned roles/permission
     * @return array
     */
    public function getItems_($model)
    {
        $manager = Configs::authManager();
        $available = [];
        foreach (array_keys($manager->getRoles()) as $name) {
            $available[$name] = 'role';
        }

        foreach (array_keys($manager->getPermissions()) as $name) {
            if ($name[0] != '/') {
                $available[$name] = 'permission';
            }
        }

        $assigned = [];
        foreach ($manager->getAssignments($model->id) as $item) {
            $assigned[$item->roleName] = $available[$item->roleName];
            unset($available[$item->roleName]);
        }

        return [
            'available' => $available,
            'assigned' => $assigned,
        ];
    }

    /**
     * Assign items
     * @param string $id
     * @return array
     */
    public function actionAssign($id)
    {
        $items = \Yii::$app->getRequest()->post('items', []);
        $res = [];
        if (empty($items[0])){//没有选择角色
            $res['data'] = "请选择角色";
            $res['res'] = 0;
            return json_encode($res);
        }
        $model = new Assignment($id);
        $success = $model->assign($items);
        $res['data'] = "";
        $res['items'] = $items;
        $res['res'] = $success>0?1:0;
        return json_encode($res);
    }

    /**
     * Assign items
     * @param string $id
     * @return array
     */
    public function actionUnassign($id)
    {
        $items = \Yii::$app->getRequest()->post('items', []);
        $res = [];
        if (empty($items[0])){//没有选择角色
            $res['data'] = "请选择角色";
            $res['res'] = 0;
            return json_encode($res);
        }
        $model = new Assignment($id);
        $success = $model->revoke($items);
        $res['data'] = "";
        $res['items'] = $items;
        $res['res'] = $success>0?1:0;
        return json_encode($res);
    }

    /**
     * Deletes an existing AuthItem model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param  string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (!empty($id)){
            $user = User::findOne($id);
            $res = $user->delete();
            if ($res){
                $res['data'] = "";
                $res['res'] = 1;
            }else{
                $res['data'] = "";
                $res['res'] = 0;
            }
            return json_encode($res);
        }
    }

    /**
     * 拿到树
     */
    public function actionGetTree(){
        $item = new AuthItem();
        $items = $item->findBysql('select name,description,type from auth_item where left(name,1)!="/"')->asArray()->all();
        $child = new AuthItemChild();
        $childs = $child->find()->asArray()->all();
        $childs_ = [];
        $res = [];
        foreach ($childs as $kk=>$vv){
            $childs_[$vv['parent']]['child'] = $vv['parent'];
            $childs_[$vv['parent']]['index'] = $kk;
        }
        $i_ = 0;
        $res = [];
        foreach ($items as $k=>$v){
            if ($v['type']==1){
                $i__ = 0;
                foreach ($childs as $kk=>$vv){
                    if ($v['name'] == $vv['parent']){
                        $res[$i_]['label'] = $vv['parent'];
                        if (subStr($vv['child'],0,1)!='/'){
                            $res[$i_] ['children'][$i__]['label'] = $vv['child'];
                            $res[$i_] ['children'][$i__] = $this->xunhuan($childs,$vv,0,0,$res[$i_] ['children'][$i__]);
                            $i__++;
                        }
                    }
                }
                $i_++;
            }
        }
        $ress['data'] = $res;
        $ress['res'] = 1;
        return json_encode($ress);
    }

    /**
     * 循环
     * @param $childs
     * @param $vv
     * @param $i_
     * @param $i__
     * @param $res
     * @return mixed
     */
    public function xunhuan($childs,$vv,$i_,$i__,$res){
        foreach ($childs as $kkk=>$vvv){
            if ($vvv['parent']==$vv['child']){
                if (subStr($vvv['child'],0,1)!='/'){
                    $res['children'][$i__]['label'] = $vvv['child'];
                    $res['children'][$i__] = $this->xunhuan($childs,$vvv,$i_,$i__,$res['children'][$i__]);
                    $i__++;
                }
            }
        }
        return $res;
    }

    /**
     * Finds the AuthItem model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return AuthItem the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        $auth = Configs::authManager();
        $item = $this->type === Item::TYPE_ROLE ? $auth->getRole($id) : $auth->getPermission($id);
        if ($item) {
            return new AuthItem($item);
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}